<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Codex extends Controller_Template {
	
	public function __construct(Kohana_Request $request)
	{
		parent::__construct($request);
		Database::instance()->query(Database::UPDATE, "SET NAMES 'utf8'", false);
	}
	
	public function action_index()
	{
		$q = null;
		
		$view = View::factory('search');
		
		if(Arr::get($_GET, 'q'))
		{
			$q = trim(Arr::get($_GET, 'q'));
			$q_terms = preg_replace("/[^A-Za-z0-9\s]/", "", $q);
			
			$search_terms = explode(" ", $q_terms);
			
			$fulltext_search = "+".implode("* +", $search_terms)."*";
			
			$query = DB::select()->from('people');
			
			if(false)
			{
				// Use LIKE operator
				
				// for($i=0; $i< count($search_terms); $i++)
				// 	$query->where('name', 'LIKE', '%'.$search_terms[$i].'%');
			}
			else
			{
				// Use FULLTEXT search
				
				$query->where(DB::expr('MATCH(people.name)'), '', DB::expr("AGAINST(".Database::instance()->escape($fulltext_search)." IN BOOLEAN MODE)"));
				//echo Kohana::debug($query->execute());			
				//echo Kohana::debug($fulltext_search);
			}
			
			$pagination = Pagination::factory(array(
				'total_items' => $query->execute()->count(),
				'items_per_page' => 20,
			));
			
			$query->order_by('name', 'ASC');
						
			$results = $query
						->limit($pagination->items_per_page)
						->offset($pagination->offset)
						->as_object('Model_Person')
						->execute();
								
			$results_view = View::factory('results')->set('results', $results);
			$view->results = $results_view;
			
			$this->template->set_global('pagination', $pagination->render());
			$this->template->set_global('total_items', $pagination->total_items);
		}
		
		$this->template->copy = $view;
		$this->template->set_global('q', $q);
	}
	
	public function action_person($id)
	{
		$headers = apache_request_headers();

		// Perform content negotiation
		$accepts = arr::get($headers, 'Accept', 'text/html');

		$redirect = URL::base()."person/$id.html";
		
		if(stripos($accepts, "application/rdf+xml") !== FALSE)
			$redirect = URL::base()."person/$id.rdf";
			
		$this->request->status = 303;
		$this->request->headers['Location'] = $redirect;
		
		$this->template = View::factory('person_303')->set('redirect', $redirect);
	}
	
	public function action_person_html($id)
	{
		$person = ORM::factory('person', array('musicnetid' => "$id"));
		
		// Groups the variants
		$variants = array();
		$musicnet_links = array();
		
		foreach($person->variants->find_all() as $v)		
		{
			if(!isset($variants[$v->catalog]))
				$variants[$v->catalog] = array();
				
			$variants[$v->catalog][] = $v;
			$musicnet_links[] = $v->link();
		}
		
		// Get additional links from RDF
		$parser = ARC2::getRDFParser();
		$parser->parse(DOCROOT."person/$id.rdf");
		$index = $parser->getSimpleIndex();
		
		// Regexes to match all known links (give titles)
		$known_links = array(
			"/bbc\.co\.uk/" => "BBC",
			"/dbpedia\.org/" => "DBPedia",
			"/imdb\.com/" => "IMDB",
			"/wikipedia\.org/" => "Wikipedia",
			"/pbs\.org/" => "PBS",
			"/britannica\.com/" => "Encylopedia Britannica",
			"/nytimes\.com/" => "New York Times",
		);
		
		$links = array();
		
		if(count($index) && isset($index["http://musicnet.mspace.fm/person/$id#id"]))
		{
			$info = $index["http://musicnet.mspace.fm/person/$id#id"];
			
			if(isset($info['http://xmlns.com/foaf/0.1/page']))
				$foaf = $info['http://xmlns.com/foaf/0.1/page'];
				
			// Build an array of additional links
			$foaf = array_diff($foaf, $musicnet_links);

			foreach($foaf as $l)
			{
				if(preg_match("/musicnet\.mspace/", $l))
					continue;
				
				$k = "Biography";
				
				foreach($known_links as $regex => $title)
				{
					if(preg_match($regex, $l))
						$k = $title;
				}
				
				$links[] = array('link' => $l, 'title' => $k);
			}

			ksort($links);
		}
		
		
		
		$this->template->copy = View::factory('person')->set('person', $person)->set('variants', $variants)->set('links', $links);
	}
	
	public function action_list($alpha)
	{
		$results = ORM::factory('person')->where('a2z', '=', $alpha)->find_all();
		
		$pagination = Pagination::factory(array(
			'total_items' => $results->count(),
			'items_per_page' => 20,
		));
					
		$results = ORM::factory('person')
							->where('a2z', '=', $alpha)
							->limit($pagination->items_per_page)
							->offset($pagination->offset)
							->order_by('name', 'ASC')
							->find_all();
		
		$view = View::factory('list');
		
		$results_view = View::factory('results')->set('results', $results);
		$view->results = $results_view;
		
		$this->template->copy = $view;
		
		$this->template->set_global('pagination', $pagination->render());
		$this->template->set_global('total_items', $pagination->total_items);
	}

} // End Welcome
